// 做插件库 传送门 suspense
// vue3 写安卓和ios原生 react react native
// https://www.axios-http.cn/
// https://www.typescriptlang.org/zh/docs/
import axios, { type AxiosInstance } from 'axios'
import { useCache } from '../utils/useCache'

// 取消接口的方式 controller.abort()
let controller = new AbortController()

export const abort = () => {
    controller.abort()
    controller = new AbortController()
}

const instance: AxiosInstance = axios.create({
    baseURL: '/',
    timeout: 10000,
    headers: { 'X-Custom-Header': 'foobar' }
})

instance.interceptors.request.use(
    (config) => config,
    (error) => Promise.reject(error)
)

instance.interceptors.response.use(
    (response) => {
        // 打印接口返回结果
        const { url = '', method = '', params } = response.config
        const { data } = response
        console.groupCollapsed(
            `%c${method}: ${url}: ${JSON.stringify(params || {})}`,
            'color: #4b4bc4'
        )
        console.log('params', params)
        console.log('data', data)
        console.groupEnd()
        return response.data
    },
    (error) => Promise.reject(error)
)

interface Options {
    cancel?: boolean
    cache?: boolean
    [key: string]: any
}

export const request = (url: string, method: string, params?: any, options?: Options) => {
    // 获取缓存数据 - start -
    const getCacheData = useCache({ url, method, params })
    const data = getCacheData(options?.cache || false)
    if (data) {
        return Promise.resolve(data)
    }
    // 获取缓存数据 - end -
    return instance({
        method,
        url,
        data: params,
        params,
        signal: controller.signal
    }).then((data: any) => {
        // 设置缓存数据 - start -
        const setCacheData = useCache({ url, method, params, data })
        setCacheData(options?.cache || false)
        // 设置缓存数据 - end -
        return data
    })
}

export const get = (url: string, params?: any, options?: Options) => {
    return request(url, 'GET', params, options)
}

export const post = (url: string, params?: any, options?: Options) => {
    return request(url, 'POST', params, options)
}
